﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Acms.SqlDal;

namespace Acms.Bll
{
    public class Redirect : BaseItem
    {
        protected Redirect() : base() { }

        protected Redirect(Hashtable table) : base(table) { }

        protected Redirect(Hashtable table, ICollection collection) : base(table, collection) { }

        public static Redirect CreateInstance()
        {
            return new Redirect();
        }

        protected override Acms.SqlDal.Base CreateDal()
        {
            return new Acms.SqlDal.RedirectDal();
        }

        private static Redirect Get(Hashtable table)
        {
            if (table == null)
            {
                return null;
            }
            else
            {
                return new Redirect(table);
            }

        }

        private static List<Redirect> Get(Hashtable[] tables)
        {
            if (tables == null)
            {
                return null;
            }
            else
            {
                var tmp = new List<Redirect>();
                foreach (Hashtable table in tables)
                {
                    tmp.Add(new Redirect(table, tmp));
                }
                return tmp;
            }
        }

        protected override void Load(Hashtable table)
        {
            Id = (int)table[RedirectDal.Fields.Id];
            SiteId = (int)table[RedirectDal.Fields.SiteId];
            OriginalUrl = (string)table[RedirectDal.Fields.OriginalUrl];
            TargetUrl = (string)table[RedirectDal.Fields.TargetUrl];
            HttpCode = (int)table[RedirectDal.Fields.HttpCode];
        }


        public static List<Redirect> GetAllBySiteId(int siteId)
        {
            RedirectDal dal = new RedirectDal();
            return Get(dal.GetAllBySiteId(siteId));
        
        }

        public static List<Redirect> GetAllBySiteUrl(string siteUrl)
        {
            RedirectDal dal = new RedirectDal();
            return Get(dal.GetAllBySiteUrl(siteUrl));
        }

        public int Id { get; private set; }
        public int SiteId { get; private set; }
        public string OriginalUrl { get; private set; }
        public string TargetUrl { get; private set; }
        public int HttpCode { get; private set; }

        public string GetFullUrl(string serverProtocol,string siteUrl)
        {
            if (OriginalUrl.Contains("://"))
                return OriginalUrl;
            else if(OriginalUrl.StartsWith("~/")|| OriginalUrl.StartsWith("?") || OriginalUrl.StartsWith("*"))
                return string.Concat(serverProtocol, siteUrl, OriginalUrl.Replace("~/", "/"));
            else
                return string.Concat(serverProtocol, siteUrl, OriginalUrl);
        }
    }
}
